package com.rightsidetech.activity.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.activity.dto.request.ActActivityAuditRecordReq;
import com.rightsidetech.activity.dto.request.MtActivityBaseInfoFindReq;
import com.rightsidetech.activity.dto.request.MtActivityBaseInfoInsertReq;
import com.rightsidetech.activity.dto.request.MtActivityBaseInfoUpdateReq;
import com.rightsidetech.activity.dto.request.store.*;
import com.rightsidetech.activity.dto.response.ActActivityAuditRecordResp;
import com.rightsidetech.activity.dto.response.MtActivityBaseInfoPageResp;
import com.rightsidetech.activity.dto.response.MtActivityServiceDetailResp;
import com.rightsidetech.activity.dto.response.mtUserJoinActivityPrizeResp;
import com.rightsidetech.activity.dto.response.store.*;
import com.rightsidetech.activity.entity.*;
import com.rightsidetech.activity.mapper.*;
import com.rightsidetech.activity.service.MtActivityService;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.enums.StoreActivityEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: yhr
 * @Date: 2022-02-08 15:38
 */
@Service("mtActivityService")
public class MtActivityServiceImpl implements MtActivityService {
    @Resource
    private MtActivityMapper mtActivityMapper;
    @Resource
    private MtActivityRuleMapper mtActivityRuleMapper;
    @Resource
    private MtActivityRuleDetailMapper mtActivityRuleDetailMapper;
    @Resource
    private ActActivityRelationMapper actActivityRelationMapper;
    @Resource
    private MtUserJoinActivityProcessMapper mtUserJoinActivityProcessMapper;
    @Resource
    private MtUserJoinActivityApplyMapper mtUserJoinActivityApplyMapper;
    @Resource
    private MtActivityRuleBusinessMapper mtActivityRuleBusinessMapper;
    @Resource
    private ActActivityAuditRecordMapper actActivityAuditRecordMapper;
    @Resource
    private MtActivityBaseInfoMapper mtActivityBaseInfoMapper;
    @Resource
    private MtUserJoinActivityPrizeMapper mtUserJoinActivityPrizeMapper;



    @Override
    public ResponseData<PageInfo<MtActivityServicePageResp>> page(MtActivityServicePageReq req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<MtActivityServicePageResp> pages = mtActivityMapper.page(req);
/*        for (MtActivityServicePageResp resp : pages) {
            resp.setActivityTime(resp.getStartTime() + "至" + resp.getEndTime());
            resp.setActivityRule(mtActivityRuleMapper.selectRule(resp.getActId(), StoreActivityEnum.HJ000.getDicType()));
            resp.setJoinRule(mtActivityRuleMapper.selectRule(resp.getActId(), StoreActivityEnum.CY000.getDicType()));
            resp.setRewardRule(mtActivityRuleMapper.selectRule(resp.getActId(), StoreActivityEnum.JL000.getDicType()));
        }*/
        return ResponseData.success(new PageInfo<>(pages));
    }

    @Override
    public ResponseData<PageInfo<MtActivityServiceInfoPageResp>> activityInfoPage(MtActivityServiceInfoPageReq req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<MtActivityServiceInfoPageResp> pages = mtActivityMapper.activityInfoPage(req);
        for (MtActivityServiceInfoPageResp resp : pages) {
            resp.setActivityTime(resp.getStartTime() + "至" + resp.getEndTime());
            Map<String, String> nameRule = mtActivityRuleMapper.selectNameRule(resp.getActId(), StoreActivityEnum.HJ000.getDicType());
            Map<String, String> nameRule2 = mtActivityRuleMapper.selectNameRule(resp.getActId(), StoreActivityEnum.CJ001.getDicType());
            Map<String, String> nameRule3 = mtActivityRuleMapper.selectNameRule(resp.getActId(), StoreActivityEnum.MB000.getDicType());
            Map<String, String> nameRule4 = mtActivityRuleMapper.selectNameRule(resp.getActId(), StoreActivityEnum.JF000.getDicType());
            resp.setActivityRule(nameRule.get("conditions"));
            resp.setJoinRule(mtActivityRuleMapper.selectRule(resp.getActId(), StoreActivityEnum.CY000.getDicType()));
            resp.setRewardRule(mtActivityRuleMapper.selectRule(resp.getActId(), StoreActivityEnum.JL000.getDicType()));
            if ((!StringUtils.isEmpty(nameRule2) && (StoreActivityEnum.CJ001.getDicCode().equals(nameRule2.get("expressionField")) || StoreActivityEnum.CJ003.getDicCode().equals(nameRule2.get("expressionField")))) && resp.getStatus() == 0) {
                resp.setVerify((byte) 0);
            } else {
                resp.setVerify((byte) 1);
            }
            if (!StringUtils.isEmpty(nameRule2) && StoreActivityEnum.CJ002.getDicCode().equals(nameRule2.get("expressionField"))) {
                Long countNum = mtUserJoinActivityPrizeMapper.selectCountNumByActivityIdAndUserAccountId(resp.getActId(), resp.getStoreId());
                resp.setCountNum(countNum);
            }

            if (!StringUtils.isEmpty(nameRule2) && StoreActivityEnum.CJ001.getDicCode().equals(nameRule2.get("expressionField"))) {
                MtUserJoinActivityProcess mtUserJoinActivityProcess = mtUserJoinActivityProcessMapper.selectByActIdAndStoreId(resp.getActId(), resp.getStoreId());
                resp.setCountNum((long) mtUserJoinActivityProcess.getBizValue());
            }

            if (!StringUtils.isEmpty(nameRule4)) {
                if (StoreActivityEnum.JF001.getDicCode().equals(nameRule4.get("expressionField"))) {
                    resp.setRewardWay(StoreActivityEnum.JF001.getDicValue());
                }
                if (StoreActivityEnum.JF002.getDicCode().equals(nameRule4.get("expressionField"))) {
                    resp.setRewardWay(StoreActivityEnum.JF002.getDicValue());
                }
                if (StoreActivityEnum.JF003.getDicCode().equals(nameRule4.get("expressionField"))) {
                    resp.setRewardWay(StoreActivityEnum.JF003.getDicValue());
                }
                if (StoreActivityEnum.JF004.getDicCode().equals(nameRule4.get("expressionField"))) {
                    resp.setRewardWay(StoreActivityEnum.JF004.getDicValue());
                }
            }
            if (!StringUtils.isEmpty(nameRule3)) {
                //判断模版名
                if (StoreActivityEnum.MB001.getDicCode().equals(nameRule3.get("expressionField"))) {
                    resp.setPosterPicName(StoreActivityEnum.MB001.getDicValue());
                }
                if (StoreActivityEnum.MB002.getDicCode().equals(nameRule3.get("expressionField"))) {
                    resp.setPosterPicName(StoreActivityEnum.MB002.getDicValue());
                }
                if (StoreActivityEnum.MB003.getDicCode().equals(nameRule3.get("expressionField"))) {
                    resp.setPosterPicName(StoreActivityEnum.MB003.getDicValue());
                }
                if (StoreActivityEnum.MB004.getDicCode().equals(nameRule3.get("expressionField"))) {
                    resp.setPosterPicName(StoreActivityEnum.MB004.getDicValue());
                }
                if (StoreActivityEnum.MB005.getDicCode().equals(nameRule3.get("expressionField"))) {
                    resp.setPosterPicName(StoreActivityEnum.MB005.getDicValue());
                }
            }
            if (StoreActivityEnum.HJ002.getDicCode().equals(nameRule.get("expressionField"))) {
                resp.setCountNum(mtUserJoinActivityProcessMapper.selectBizValue(resp.getActId(), resp.getStoreId()));
            }
            //awardRule 获奖标准(1订单 2赞数 3天数 4销量)
            if (!StringUtils.isEmpty(nameRule) && !StringUtils.isEmpty(nameRule.get("expressionField"))) {
                if (StoreActivityEnum.HJ001.getDicCode().equals(nameRule.get("expressionField"))) {
                    resp.setAwardRule(StoreActivityEnum.HJ001.getDicValue());
                }
                if (StoreActivityEnum.HJ002.getDicCode().equals(nameRule.get("expressionField"))) {
                    resp.setAwardRule(StoreActivityEnum.HJ002.getDicValue());
                }
                if (StoreActivityEnum.HJ003.getDicCode().equals(nameRule.get("expressionField"))) {
                    resp.setAwardRule(StoreActivityEnum.HJ003.getDicValue());
                }
                if (StoreActivityEnum.HJ004.getDicCode().equals(nameRule.get("expressionField"))) {
                    resp.setAwardRule(StoreActivityEnum.HJ004.getDicValue());
                }
            }
        }
        return ResponseData.success(new PageInfo<>(pages));
    }

    @Override
    public Long saveMtActivity(MtActivity req) {
        mtActivityMapper.insertSelective(req);
        return req.getId();
    }

    @Override
    public int updateMtActivity(MtActivity req) {
        return mtActivityMapper.updateByPrimaryKeySelective(req);
    }

    @Override
    public int saveMtActivityRule(MtActivityRule req) {
        return mtActivityRuleMapper.insertSelective(req);
    }

    @Override
    public MtActivity selectByName(String name) {
        return mtActivityMapper.selectByName(name);
    }

    @Override
    public MtActivityRule selectByActId(Long actId, String modId) {
        return mtActivityRuleMapper.selectActRule(actId, modId);
    }

    @Override
    public int saveMtActivityRuleDetail(MtActivityRuleDetailWithBLOBs req) {
        return mtActivityRuleDetailMapper.insertSelective(req);
    }

    @Override
    public int updateMtActivityRuleDetail(MtActivityRuleDetailWithBLOBs req) {
        return mtActivityRuleDetailMapper.updateByActId(req);
    }

    @Override
    public ResponseData<MtActivityServiceDetailResp> activityInfo(Long activityId) {
        String str = mtActivityRuleDetailMapper.selectReqById(activityId);
        MtActivityServiceSaveReq a = JSONUtil.toBean(str, MtActivityServiceSaveReq.class);
        MtActivityServiceDetailResp mtActivityServiceDetailResp = BeanUtil.copyProperties(a, MtActivityServiceDetailResp.class);
        mtActivityServiceDetailResp.setJoinRuleName(StringUtils.isEmpty(a.getJoinRule()) ? null : (a.getJoinRule().equals("1") ? "区域" : "等级"));
        mtActivityServiceDetailResp.setEnrollName(StringUtils.isEmpty(a.getEnroll()) ? null : (a.getEnroll().equals("1") ? "手动报名" : "自动报名"));
        String awardRuleName = null;
        //1订单 2赞数 3天数 4销量
        if (!StringUtils.isEmpty(a.getAwardRule())) {
            switch (a.getAwardRule()) {
                case "1":
                    awardRuleName = "订单";
                    break;
                case "2":
                    awardRuleName = "赞数";
                    break;
                case "3":
                    awardRuleName = "天数";
                    break;
                case "4":
                    awardRuleName = "销量";
                    break;
            }
        }

        mtActivityServiceDetailResp.setAwardRuleName(awardRuleName);
        mtActivityServiceDetailResp.setRewardName(StringUtils.isEmpty(a.getReward()) ? null : (a.getReward().equals("1") ? "现金" : "积分"));

        mtActivityServiceDetailResp.setCompareName(StringUtils.isEmpty(a.getCompare()) ? null : (a.getCompare().equals("1") ? "全部排名" : "大区排名"));
        String rewardWayName = null;
        //1平分 2随机 3固定 4固定随机
        if (!StringUtils.isEmpty(a.getRewardWay())) {
            switch (a.getRewardWay()) {
                case "1":
                    rewardWayName = "平分";
                    break;
                case "2":
                    rewardWayName = "随机";
                    break;
                case "3":
                    rewardWayName = "固定";
                    break;
                case "4":
                    rewardWayName = "固定随机";
                    break;
            }
        }
        mtActivityServiceDetailResp.setRewardWayName(rewardWayName);
        mtActivityServiceDetailResp.setPaymentName(StringUtils.isEmpty(a.getPayment()) ? null : (a.getPayment().equals("1") ? "手动打款" : "自动打款"));
        String attendName = null;
        if (!StringUtils.isEmpty(a.getAttend())) {
            switch (a.getAttend()) {
                case "1":
                    attendName = "上传图片";
                    break;
                case "2":
                    attendName = "抽奖";
                    break;
                case "3":
                    attendName = "连续上传图片";
                    break;
            }
        }

        mtActivityServiceDetailResp.setAttendName(attendName);
        mtActivityServiceDetailResp.setActId(activityId);

        MtActivity mtActivity = mtActivityMapper.selectByPrimaryKey(activityId);
        if (!StringUtils.isEmpty(mtActivity)) {
            mtActivityServiceDetailResp.setStatus(mtActivity.getStatus());
            mtActivityServiceDetailResp.setRejectReason(mtActivity.getRejectReason());
        }

        return ResponseData.success(mtActivityServiceDetailResp);
    }

    @Override
    public ResponseData verify(MtActivityVerifyReq req) {
        MtActivity mtActivity = mtActivityMapper.selectByPrimaryKey(req.getActId());
        if (mtActivity.getStatus() != 0) {
            return ResponseData.fail("该活动不处于待审核状态");
        }
        mtActivityMapper.updateVerify(req);
        return ResponseData.success();
    }

    @Override
    public ResponseData verifyImg(MtActivityVerifyImgReq req, Long loginInfoId, String loginName) {
        MtUserJoinActivityApply apply = mtUserJoinActivityApplyMapper.selectByActIdAndUserId(req.getActId(), req.getStoreId());
        if (ObjectUtils.isEmpty(apply)) {
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        if (apply.getStatus() != 0) {
            return ResponseData.fail("当前状态无法审核");
        }

        MtUserJoinActivityApply apply1 = new MtUserJoinActivityApply();
        apply1.setId(apply.getId());
        apply1.setRejectReason(req.getRejectReason());
        if (req.getStatus() == 1) {
            //审核通过
            //判断是否打钱,奖励规则为积分/现金
//            mtUserJoinActivityApplyMapper.updateStatus(apply.getId(), (byte) 1,req.getRejectReason());
            apply1.setStatus((short) 1);
            if (!StringUtils.isEmpty(req.getNum())) {
                mtUserJoinActivityProcessMapper.updateBizValue(req.getNum(), req.getActId(), req.getStoreId());
            }
        } else {
            //审核不通过
//            mtUserJoinActivityApplyMapper.updateStatus(apply.getId(), (byte) -1,req.getRejectReason());
            apply1.setStatus((short) 2);
        }
        apply1.setVerifyId(loginInfoId);
        apply1.setVerifyName(loginName);
        apply1.setVerifyAt(new Date());

        mtUserJoinActivityApplyMapper.updateByPrimaryKeySelective(apply1);

        return ResponseData.success();
    }

    @Override
    public int delRule(Long actId) {
        return mtActivityRuleMapper.deleteByActId(actId);
    }

    @Override
    public ResponseData delActivity(Long actId) {
        MtActivity mtActivity = mtActivityMapper.selectByPrimaryKey(actId);
        if (ObjectUtils.isEmpty(mtActivity)) {
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        mtActivityMapper.updateDel(actId);
        mtActivityRuleMapper.deleteByActId(actId);
        mtActivityRuleDetailMapper.deleteByActId(actId);
        return ResponseData.success();
    }

    @Override
    public void activityRelation(Long activityId, String areaIds, String agentIds) {
        ActActivityRelationWithBLOBs actId = actActivityRelationMapper.selectByActId(activityId, (byte) 2);
        if (ObjectUtils.isEmpty(actId)) {
            ActActivityRelationWithBLOBs relation = new ActActivityRelationWithBLOBs();
            relation.setType((byte) 2);
            relation.setRelationId(activityId);
            relation.setCreatedAt(new Date());
            relation.setAreaIdArray(areaIds);
            relation.setAgentIdArray(agentIds);
            actActivityRelationMapper.insertSelective(relation);
        } else {
            ActActivityRelationWithBLOBs relation = new ActActivityRelationWithBLOBs();
            relation.setType((byte) 2);
            relation.setRelationId(activityId);
            relation.setCreatedAt(new Date());
            relation.setAreaIdArray(areaIds);
            relation.setAgentIdArray(agentIds);
            actActivityRelationMapper.updateByPrimaryKeyWithBLOBs(relation);
        }
    }

    @Override
    public MtActivity selectById(Long actId) {
        return mtActivityMapper.selectByPrimaryKey(actId);
    }

    @Override
    public ResponseData selectDateByActId(Long actId, Byte type) {
        return null;
    }

    @Override
    public MtActivityRule selectRule(Long actId, String mold) {
        return mtActivityRuleMapper.selectActRule(actId, mold);
    }

    @Override
    public PageInfo<Long> selectBizId(MtActivityActStoreIdReq req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<Long> longs = mtUserJoinActivityProcessMapper.selectBizId(req);
        return new PageInfo<>(longs);
    }

    @Override
    public List<MtAwardImgResp> selectImgBizId(Long actId, Long storeId) {
        return mtUserJoinActivityProcessMapper.selectImgBizId(actId, storeId);
    }

    @Override
    public PageInfo<MtActivityEndPageResp> activityEndPage(MtActivityEndPageReq req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<MtActivityEndPageResp> pages = mtActivityMapper.activityEndPage(req);
        return new PageInfo<>(pages);
    }

    @Override
    public ResponseData<PageInfo<MtActivityEndInfoResp>> activityEndInfoPage(MtActivityActIdReq req, List<Long> areaIds, MtActivityRule rule) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<MtActivityEndInfoResp> infoResps = null;
        if (ObjectUtils.isEmpty(rule)) {
            infoResps = mtUserJoinActivityApplyMapper.activityEndInfoPage(req);
        } else if (StoreActivityEnum.PB001.getDicCode().equals(rule.getExpressionField())) {
            //全部排名
            return ResponseData.success(new PageInfo<>(sort(rule, req, null)));
        } else if (StoreActivityEnum.PB002.getDicCode().equals(rule.getExpressionField())) {
            //大区排名
            return ResponseData.success(new PageInfo<>(sort(rule, req, areaIds)));
        }
        return ResponseData.success(new PageInfo<>(infoResps));
    }

    private List<MtActivityEndInfoResp> sort(MtActivityRule rule, MtActivityActIdReq req, List<Long> areaIds) {
        List<MtActivityEndInfoResp> endResps = mtUserJoinActivityApplyMapper.activityCompareEndPage(req, null, areaIds);
        if (!ObjectUtils.isEmpty(endResps)) {
            Long topOrder = endResps.get(Integer.parseInt(rule.getConditionValue())).getCountNum();
            Long topOrder1 = endResps.get(Integer.parseInt(rule.getConditionValue()) + 1).getCountNum();
            if (topOrder.equals(topOrder1)) {
                endResps.removeIf(resp -> !endResps.contains(topOrder));
                List<MtActivityEndInfoResp> resps = mtUserJoinActivityApplyMapper.activityCompareEndPage(req, Long.valueOf(rule.getConditionValue()), areaIds);
                List<MtActivityEndInfoResp> collect = Stream.of(resps, endResps).flatMap(Collection::stream).distinct().collect(Collectors.toList());
                return collect;
            }
        }
        return endResps;
    }

    @Override
    public int insertBusiness(MtActivityRuleBusiness business) {
        return mtActivityRuleBusinessMapper.insertSelective(business);
    }

    @Override
    public int deleteByActId(Long actId) {
        return mtActivityRuleBusinessMapper.deleteByActId(actId);
    }

    @Override
    public ResponseData<PageInfo<ActActivityAuditRecordResp>> findActivityAuditRecordPage(ActActivityAuditRecordReq req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<ActActivityAuditRecordResp> list = actActivityAuditRecordMapper.findPage(req);
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public void updateStatus() {
        mtActivityMapper.updateStatus();
    }

    @Override
    public void storeActivityRankingTask(List<Long> ids) {
        //查询进行中 已到结束时间活动
        List<MtActivity> list = mtActivityMapper.selectTimeOverAct();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (MtActivity activity : list) {
            //判断是否是排名活动
            MtActivityRule mtActivityRule = mtActivityRuleMapper.selectActRule(activity.getId(), StoreActivityEnum.PB000.getDicType());
            if (!ObjectUtils.isEmpty(mtActivityRule)) {
                int num1 = Integer.parseInt(mtActivityRule.getConditionValue());
                MtActivityRule rule = mtActivityRuleMapper.selectActRule(activity.getId(), StoreActivityEnum.HJ001.getDicType());
                if (!ObjectUtils.isEmpty(rule)) {
                    int num2 = Integer.parseInt(rule.getConditionValue());
                    //全部排名
                    if (mtActivityRule.getExpressionField().equals(StoreActivityEnum.PB001.getDicCode())) {
                        //销量规则 和 排名规则 获取达标门店
                        List<MtavtivityRankResp> respList = mtUserJoinActivityProcessMapper.findRankingByRule(activity.getId(), num1, num2, null);
                        if (!CollectionUtils.isEmpty(respList)) {
                            //达标 修改状态
                            for (MtavtivityRankResp rankResp : respList) {
                                mtUserJoinActivityApplyMapper.updateStatusByActIdAndStoreId(activity.getId(), rankResp.getStoreId(), (short) 1);
                            }
                        }
                    } else {
                        if (CollectionUtils.isEmpty(ids)) {
                            return;
                        }
                        //大区排名
                        for (Long areaId : ids) {
                            List<MtavtivityRankResp> respList = mtUserJoinActivityProcessMapper.findRankingByRule(activity.getId(), num1, num2, areaId);
                            if (!CollectionUtils.isEmpty(respList)) {
                                //达标 修改状态
                                for (MtavtivityRankResp rankResp : respList) {
                                    mtUserJoinActivityApplyMapper.updateStatusByActIdAndStoreId(activity.getId(), rankResp.getStoreId(), (short) 1);
                                }
                            }
                        }
                    }
                }
            }
        }
        //到活动结束时间 修改状态
        mtActivityMapper.updateStatus();
    }


    @Override
    public ResponseData inserActivityBaseInfo(MtActivityBaseInfoInsertReq req, Long loginId, String loginName) {

        MtActivityBaseInfo mtActivityBaseInfo2 = mtActivityBaseInfoMapper.selectByBaseName(req.getBaseName());
        if (!StringUtils.isEmpty(mtActivityBaseInfo2)) {
            return ResponseData.fail("名称已存在");
        }

        MtActivityBaseInfo mtActivityBaseInfo = new MtActivityBaseInfo();
        BeanUtils.copyProperties(req, mtActivityBaseInfo);
        mtActivityBaseInfo.setCreatedAt(new Date());
        mtActivityBaseInfo.setCreaterId(loginId);
        mtActivityBaseInfo.setCreaterName(loginName);

        int count = mtActivityBaseInfoMapper.insertSelective(mtActivityBaseInfo);
        if (count > 0) {
            return ResponseData.success();
        }
        return ResponseData.fail();
    }

    @Override
    public ResponseData updateActivityBaseInfo(MtActivityBaseInfoUpdateReq req, Long loginId, String loginName) {
        MtActivityBaseInfo mtActivityBaseInfo2 = mtActivityBaseInfoMapper.selectByBaseName(req.getBaseName());
        if (!StringUtils.isEmpty(mtActivityBaseInfo2) && !req.getId().equals(mtActivityBaseInfo2.getId())) {
            return ResponseData.fail("名称已存在");
        }
        MtActivityBaseInfo mtActivityBaseInfo = new MtActivityBaseInfo();
        BeanUtils.copyProperties(req, mtActivityBaseInfo);
        mtActivityBaseInfo.setUpdatedAt(new Date());
        mtActivityBaseInfo.setUpdaterId(loginId);
        mtActivityBaseInfo.setUpdaterName(loginName);

        int count = mtActivityBaseInfoMapper.updateByPrimaryKey2(mtActivityBaseInfo);
        if (count > 0) {
            return ResponseData.success();
        }
        return ResponseData.fail();
    }

    @Override
    public ResponseData delActivityBaseInfo(Long id) {
        MtActivityBaseInfo mtActivityBaseInfo2 = mtActivityBaseInfoMapper.selectByPrimaryKey(id);
        if (StringUtils.isEmpty(mtActivityBaseInfo2)) {
            return ResponseData.fail("模版不存在");
        }
        int count = mtActivityBaseInfoMapper.deleteByPrimaryKey(id);
        if (count > 0) {
            return ResponseData.success();
        }
        return ResponseData.fail();
    }

    @Override
    public ResponseData<PageInfo<MtActivityBaseInfoPageResp>> findActivityBaseInfoPage(MtActivityBaseInfoFindReq req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<MtActivityBaseInfoPageResp> pages = mtActivityBaseInfoMapper.selectList(req);
        return ResponseData.success(new PageInfo<>(pages));

    }

    @Override
    public ResponseData<PageInfo<mtUserJoinActivityPrizeResp>> findMtUserJoinActivityProcess(MtActivityActStoreIdReq req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<mtUserJoinActivityPrizeResp> list = mtUserJoinActivityPrizeMapper.selectMtUserJoinActivityPrize(req);
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public List<MtActivityRule> selectRuleAll(Long actId, String dicType) {
        return mtActivityRuleMapper.selectRuleList(actId, dicType);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData activityPayment(Long id, List<Long> areaIds, MtActivityRule rule,Long loginId,String loginName) {
        MtActivity activity = mtActivityMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(activity)) {
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        MtActivityActIdReq req = new MtActivityActIdReq();
        req.setActivityId(id);
        req.setPageNo(1);
        req.setPageSize(99999);
        List<MtActivityEndInfoResp> infoResps = new ArrayList<>();
        if (ObjectUtils.isEmpty(rule)) {
            List<MtActivityEndInfoResp> infoRespList = mtUserJoinActivityApplyMapper.activityEndInfoPage(req);
            if (!CollectionUtils.isEmpty(infoRespList)) {
                for (MtActivityEndInfoResp resp : infoRespList) {
                    if ("1".equals(resp.getStatus())) {
                        infoResps.add(resp);
                    }
                }
            }
        } else if (StoreActivityEnum.PB001.getDicCode().equals(rule.getExpressionField())) {
            //全部排名
            infoResps = sort(rule, req, null);
        } else if (StoreActivityEnum.PB002.getDicCode().equals(rule.getExpressionField())) {
            //大区排名
            infoResps = sort(rule, req, areaIds);
        }

        if (CollectionUtils.isEmpty(infoResps)) {
            return ResponseData.fail("没有需要打款的门店");
        }
        //判断是否是瓜分活动  瓜分活动需要计算瓜分金额
        boolean isGF = false;
        boolean isCJ = false;
        BigDecimal divideMoney = null;
        MtActivityRule activityRule = mtActivityRuleMapper.selectActRule(activity.getId(), StoreActivityEnum.JF001.getDicType());
        if (!ObjectUtils.isEmpty(activityRule) && activityRule.getExpressionField().equals(StoreActivityEnum.JF001.getDicCode())) {
            //查询总额
            MtActivityRule zeRule = mtActivityRuleMapper.selectActRule(activity.getId(), StoreActivityEnum.ZE001.getDicType());
            if (!ObjectUtils.isEmpty(zeRule)) {
                divideMoney = new BigDecimal(zeRule.getConditionValue()).divide(new BigDecimal(infoResps.size()), 2, BigDecimal.ROUND_DOWN);
                isGF = true;
            }
        }
        //积赞活动  堆头活动
        MtActivityRule jzRule = mtActivityRuleMapper.selectActRule(activity.getId(), StoreActivityEnum.HJ000.getDicType());
        if (!ObjectUtils.isEmpty(jzRule)) {
            //积赞
            if (jzRule.getExpressionField().equals(StoreActivityEnum.HJ002.getDicCode())) {
                //查询总额
                MtActivityRule zeRule = mtActivityRuleMapper.selectActRule(activity.getId(), StoreActivityEnum.ZE001.getDicType());
                if (!ObjectUtils.isEmpty(zeRule)) {
                    divideMoney = new BigDecimal(zeRule.getConditionValue()).divide(new BigDecimal(infoResps.size()), 2, BigDecimal.ROUND_DOWN);
                    isGF = true;
                }
            }
            //堆头
            if (jzRule.getExpressionField().equals(StoreActivityEnum.HJ003.getDicCode())) {
                //查询总额
                MtActivityRule zeRule = mtActivityRuleMapper.selectActRule(activity.getId(), StoreActivityEnum.ZE001.getDicType());
                if (!ObjectUtils.isEmpty(zeRule)) {
                    divideMoney = new BigDecimal(zeRule.getConditionValue());
                    isGF = true;
                }
            }

            //判断是否是抽奖活动
            MtActivityRule cjRule = mtActivityRuleMapper.selectActRule(req.getActivityId(), StoreActivityEnum.CJ002.getDicType());
            if (!ObjectUtils.isEmpty(cjRule) && cjRule.getExpressionField().equals(StoreActivityEnum.CJ002.getDicCode())){
                isCJ = true;
            }
        }


        for (MtActivityEndInfoResp resp : infoResps) {
            if ("1".equals(resp.getStatus())) {
                // 抽奖 已经存储该记录
                if (!isCJ){
                    MtUserJoinActivityPrize activityPrize = new MtUserJoinActivityPrize();
                    activityPrize.setActId(resp.getActivityId());
                    activityPrize.setActName(resp.getActivityName());
                    activityPrize.setActStart(activity.getStartTime());
                    activityPrize.setActEnd(activity.getEndTime());
                    activityPrize.setUserAccountId(resp.getStoreId());
                    activityPrize.setUserLoginName(resp.getStoreName());
                    activityPrize.setUserPhone(resp.getPhone());
                    activityPrize.setBizId(activity.getId());
                    activityPrize.setPrize(isGF ? divideMoney.toString() : resp.getReward());
                    activityPrize.setCreatedAt(new Date());
                    mtUserJoinActivityPrizeMapper.insertSelective(activityPrize);
                }
                //修改状态
                mtUserJoinActivityApplyMapper.updateStatusByActIdAndStoreId(resp.getActivityId(), resp.getStoreId(), (short) 3);
            }
        }
        MtActivity activity1 = new MtActivity();
        activity1.setPayerId(loginId);
        activity1.setPayerName(loginName);
        activity1.setPayerAt(new Date());
        activity1.setId(activity.getId());
        mtActivityMapper.updateByPrimaryKeySelective(activity1);

        return ResponseData.success();
    }

    @Override
    public ResponseData<List<MtActivityBannerResp>> findMtActivityBanner(MtActivityBannerReq req) {
        return ResponseData.success(mtActivityMapper.selectBannerList(req));
    }

    @Override
    public List<MtUserJoinActivityApply> selectApplyByActId(Long actId) {
        return mtUserJoinActivityApplyMapper.selectByActIdAndStatus(actId,null);
    }

    @Override
    public ResponseData insertAtActivity(ActActivityAuditRecord activityAuditRecord){
       return actActivityAuditRecordMapper.insertSelective(activityAuditRecord)>0?ResponseData.success():ResponseData.fail();
    }

    @Override
    public MtActivityBaseInfo findActivityBaseInfo(Long activityBaseInfoId) {
        return mtActivityBaseInfoMapper.selectByPrimaryKey(activityBaseInfoId);
    }


}
